<template>
  <div id="sys-log-index">
    <el-container>
      <el-main>
        <div>
          <el-form :inline="true" size="small" :model="searchForm" class="demo-form-inline"
                   @keyup.enter.native="sysLogQuery" @submit.native.prevent>
            <!-- <el-form-item v-if="userName === 'secadm' || userName === 'kfry'">
              <el-radio v-model="searchForm.logType" label="all" @change="sysLogQuery">全部</el-radio>
              <el-radio v-model="searchForm.logType" label="option" @change="sysLogQuery">操作日志</el-radio>
              <el-radio v-model="searchForm.logType" label="auth" @change="sysLogQuery">认证日志</el-radio>
            </el-form-item> -->
            <el-form-item prop="username">
              <el-input v-model="searchForm.username" placeholder="请输入用户姓名" style="width: 150px"/>
            </el-form-item>
            <el-form-item>
              <el-input v-model="searchForm.operateType" placeholder="操作行为" style="width: 150px"/>
            </el-form-item>
            <el-form-item>
              <el-input v-model="searchForm.hostIp" placeholder="IP" style="width: 150px"/>
            </el-form-item>
            <el-form-item>
              <el-select v-model="searchForm.result" clearable placeholder="结果" style="width: 80px">
                <el-option v-for="item in result" :value="item.value" :key="item.value" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="searchForm.level" clearable placeholder="风险级别" style="width: 100px">
                <el-option v-for="item in level" :value="item.id" :key="item.id" :label="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-select v-model="searchForm.behaviourType" clearable placeholder="行为类别" style="width: 120px">
                <el-option
                    v-for="item in behaviourType"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <!-- <el-select v-model="searchForm.operateType" clearable placeholder="请选择操作动作">
                  <el-option
                      v-for="item in operateType"
                      :key="item.name"
                      :label="item.name"
                      :value="item.type"
                      >
                  </el-option>
              </el-select> -->
              <el-date-picker
                  v-model="beginTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="开始时间"
                  clearable style="width: 200px">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                  v-model="endTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="结束时间"
                  clearable style="width: 200px">
              </el-date-picker>
            </el-form-item>
            <!-- <el-form-item >
                <el-select v-model="searchForm.level" clearable placeholder="请选择日志风险级别">
                    <el-option
                            v-for="item in logLevel"
                            :key="item.name"
                            :label="item.name"
                            :value="item.type"
                    >
                    </el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="sysLogQuerys">查询</el-button>
              <el-button icon="el-icon-download" v-show="!isFirstPage" type="primary" @click="exportExcel">导出</el-button>
              <el-button icon="el-icon-upload2" v-show="!isFirstPage" type="primary" @click="importExcel">导入</el-button>
              <el-button class="margin-left-10" icon="el-icon-delete" @click="sysLogReset">清空</el-button>
            </el-form-item>
            <el-tooltip effect="dark" content="刷新" placement="top-start">
              <el-button size="small" class="float-right" circle icon="el-icon-refresh"
                         @click="sysLogQuery()"></el-button>
            </el-tooltip>
          </el-form>
        </div>
        <el-table
            border
            show-header
            stripe
            :data="logList"
            size="mini"
            @selection-change="sysLogSelectionChange"
            highlight-current-row ref="sysLogTable">
          <el-table-column type="selection"  align="center">
          </el-table-column>
          <el-table-column label="序号" width="80" align="center">
            <template slot-scope="scope">
              <span>{{scope.$index+(sysLogPageData.pageInfo.current - 1) * sysLogPageData.pageInfo.size + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户" align="center" show-overflow-tooltip/>
          <!--  <el-table-column prop="roleName" label="角色" align="center" show-overflow-tooltip/>-->
          <el-table-column prop="operateModule" label="操作模块" align="center" show-overflow-tooltip/>
          <el-table-column prop="operateType" label="操作行为" align="center" show-overflow-tooltip/>
          <el-table-column prop="hostIp" label="操作ip" align="center" show-overflow-tooltip/>
          <el-table-column  label="行为类别" prop="behaviourType" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.behaviourType=='1'">一般行为</span>
              <span v-if="scope.row.behaviourType=='2'">异常行为</span>
              <span v-if="scope.row.behaviourType=='3'">告警行为</span>
            </template>
          </el-table-column>
          <el-table-column  prop="level" label="风险级别" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.level=='1'">紧急</span>
              <span v-if="scope.row.level=='2'">重要</span>
              <span v-if="scope.row.level=='3'">一般</span>
              <span v-if="scope.row.level=='4'">信息</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" align="center" show-overflow-tooltip/>
          <el-table-column prop="createTime" label="生成日期" align="center" show-overflow-tooltip/>
          <el-table-column prop="result" label="结果" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.result== 1">成功</span>
              <span v-if="scope.row.result == 2">失败</span>
            </template>
          </el-table-column>
          <!--<el-table-column label="操作" width="200px" >
              <template slot-scope="scope">
                  <el-button type="text" size="small" icon="el-icon-view" @click="look(scope.row)">查看</el-button>
                  <el-button type="text"  icon="el-icon-delete" @click="sysLogDeleteRecord(scope.row)">删除</el-button>
              </template>
          </el-table-column>-->
        </el-table>
        <el-row type="flex" justify="end" v-show="sysLogPageData.pageInfo.total>0">
          <el-pagination class="pageBar"
                         :style="{float: 'right', padding: '20px'}"
                         background
                         @size-change="sysLogSizeChange"
                         @current-change="sysLogCurrentChange"
                         :current-page="sysLogPageData.pageInfo.current"
                         :page-sizes="[10, 50, 100, 500]"
                         :page-size="sysLogPageData.pageInfo.size"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="sysLogPageData.pageInfo.total">
          </el-pagination>
        </el-row>
        <!--日志导出密码弹框-->
        <el-dialog title="设置导出日志密码" :visible.sync="passDialog" width="600px" append-to-body="true" @close="cancelDialog">
          <el-container>
            <el-main>
              <div class="dialogBox">
                <div style="text-align: center;margin-bottom: 20px;">
                  <label style="color: red">*</label> <el-input v-model="zipPass" type="password" placeholder="日志压缩包密码" style="width: 150px" />
                </div>
                <div style="text-align: center;margin-bottom: 20px;margin-left: 10px">
                  <el-button type="primary" @click="exportExcelLog">确定</el-button>
                </div>
              </div>
            </el-main>
          </el-container>
        </el-dialog>
        <!--日志导入弹框-->
        <el-dialog title="设置导入日志压缩包密码" :visible.sync="passUpDialog" width="600px" append-to-body="true" @close="cancelDialog">
          <el-container>
            <el-main>
              <div class="dialogBox">
                <div style="text-align: center;margin-bottom: 20px;">
                  <label style="color: red">*</label> <el-input v-model="zipPass" type="password" placeholder="日志压缩包密码" style="width: 150px" />
                </div>
                <div style="text-align: center;margin-bottom: 20px;margin-left: 10px">
                  <el-upload
                      class="upload-demo"
                      action="#"
                      accept=".zip"
                      :on-change="handleChange"
                      :http-request="uploadFile"
                      :show-file-list="false"
                      :auto-upload="false">
                    <el-button type="primary">上传</el-button>
                  </el-upload>
                </div>
              </div>
            </el-main>
          </el-container>
        </el-dialog>

      </el-main>
    </el-container>
  </div>
</template>

<script>
import sysLogApi from "./api/sysLog.service";
import moment from 'moment';
import {Loading} from "element-ui";

const loadingOption = {
  fullscreen: true,
  lock: true,
  text: "Loading",
  spinner: "el-icon-loading",
  background: "rgba(0, 0, 0, 0.7)"
};
let loadingInstance;

export default {
  props: {
    isFirstPage: {type: Boolean, default: false}
  },
  name: "sysLogIndex.vue",
  data() {
    return {
      passDialog: false,
      passUpDialog: false,
      zipPass: '',
      isLook: false,
      sysLogDialogData: {
        visible: false,
        sysLogTitle: "",
        sysLogFormData: {
          password: "",
          orgName: "",
          role: "",
          lockFlag: 1,
          orgId: null
        },
      },
      sysLogPageData: {
        query: {
          orgId: null,
          orgName: ""
        },
        pageInfo: {
          size: 10,
          current: 1,
          total: 0
        }
      },
      logList: [],
      searchForm: {
        // operateModule: "",
        logType: "option",
        operateType: "",
        behaviourType: "", // 级别
        // level: "",
        hostIp: "", // IP
        description: "", // 操作行为
        username: "", // 用户名
        beginTime: "",// 开始时间
        endTime: "", // 结束时间
        logZipPass: "", // zip 密码
        result: "", // 结果
      },
      fileRaw: {},
      beginTime:"",
      endTime:"",
      operateModule: [],
      operateType: [],
      behaviourType: [{id: 3, name: "一般行为"}, {id: 2, name: "异常行为"}, {id: 1, name: "违规行为"}],
      logLevel: [],
      result: [
        {
          value: '1',
          label: '成功'
        },
        {
          value: '2',
          label: '失败'
        },
      ],
      sysLogSelectIds: [], // 选择的id
      userName: '', // 当前登录的人
      level: [{id: 1, value: "紧急"}, {id: 2, value: "重要"}, {id: 3, value: "一般"}, {id: 4, value: "信息"}]
    };
  },
  created() {
    this.userName = sessionStorage.getItem("username");
    this.sysLogQuery();
    this.getLogType();
  },
  methods: {
    // 加载标示
    LoadingOpen() {
      loadingInstance = Loading.service(loadingOption);
    },
    // 加载标示关闭
    LoadingClose() {
      loadingInstance.close();
    },
    look(row) {
      this.sysLogDialogData.visible = true;
      this.sysLogDialogData.sysLogTitle = '查看';
      this.isLook = true;
      this.sysLogDialogData.sysLogFormData = row;
    },
    del(row) {
      this.$confirm('本操作将永久删除，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleNodeClick(data) {
      this.currentNode = data;
      this.sysLogPageData.query.orgId = data.id;
      this.sysLogQuery();
    },
    cancelDialog() {
      this.sysLogDialogData.visible = false;
      this.passDialog = false;
      this.passUpDialog = false;
      this.isLook = false;
      this.zipPass = "";
    },
    // 多条件查询, 上放按钮
    sysLogQuerys(){
      this.sysLogPageData.pageInfo.current = 1;
      this.sysLogQuery();
    },
    /**
     * 日志查询
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogQuery() {
      let _this = this;
      let params = {
        current: this.sysLogPageData.pageInfo.current,
        size: this.sysLogPageData.pageInfo.size
      };
      if(this.beginTime && this.endTime){
        if(this.$moment(this.beginTime).isSameOrBefore(this.endTime)){
          this.searchForm.beginTime = this.beginTime;
          this.searchForm.endTime = this.endTime;
        }else{
          this.$message.error("开始日期不能在结束日期之后");
          return false;
        }
      }else{
        if(this.beginTime){
          this.searchForm.beginTime = this.beginTime;
        }else{
          this.searchForm.beginTime = "";
        }
        if(this.endTime){
          this.searchForm.endTime = this.endTime;
        }else{
          this.searchForm.endTime = "";
        }
      }
      sysLogApi.getSysLogPage(Object.assign(params, this.searchForm)).then((res) => {
        _this.sysLogPageData.pageInfo = res.data;
        let logList = res.data.records;
        _this.logList = logList;
      })

    },
    /**
     *  导出excel
     **/
    exportExcel(){
      this.passDialog = true;
    },
    exportExcelLog(){
      if (this.zipPass === null || this.zipPass === ''){
        this.$message.warning("导出压缩包密码必填");
        return;
      }
      let _this = this;
      _this.LoadingOpen();
      this.passDialog=false;
      this.searchForm.logZipPass = this.zipPass;
      this.searchForm.logIds = this.sysLogSelectIds;
      let nowDate = moment().format("YYYYMMDDHHmmss");
      sysLogApi.exportLogExcel(this.searchForm, nowDate).then(res =>{
        _this.LoadingClose();
        _this.$refs.sysLogTable.clearSelection();
        this.searchForm.logIds = null;
      });
      // 密码置空
      // this.sysLogQuery();
    },
    /**
     *  上传excel文件
     **/
    importExcel(){
      this.passUpDialog = true;
    },
    uploadFile() {
      if (this.zipPass === ''){
        this.$message.warning("请输入压缩包密码！");
        return
      }
      let _this = this;
      _this.LoadingOpen();
      let formdata = new FormData();
      formdata.append('zipPass', this.zipPass)
      formdata.append('netExcel', this.fileRaw)
      sysLogApi.importLogExcel(formdata).then(res => {
        console.log(res);
        if (res.data.code == 10200) {
          if (res.data.data.code == 0){
            this.$message.success("导入成功");
          } else {
            this.$message.warning(res.data.data.msg);
          }
          this.passUpDialog = false;
          _this.LoadingClose();
          this.sysLogQuery();
        } else {
          _this.LoadingClose();
          if (res.data.msg) {
            this.$message.error(res.data.msg);
          }
          else {
            this.$message.error(res.data.data.msg);
          }
        }
      })
    },
    handleChange(file, fileList) {
      console.log(file, fileList);
      this.fileRaw = file.raw
      console.log(this.form);
      this.uploadFile()
    },
    getLogType() {
      let _this = this;
      sysLogApi.getLogType({}).then((res) => {
        let logList = res.data.data;
        logList.forEach(function (log) {
          if (log.type == "dict_operate_module") {
            _this.operateModule = log.dictItemVOList;
          } else if (log.type == "dict_operate_type") {
            _this.operateType = log.dictItemVOList;
          } else if (log.type == "dict_behaviour_type") {
            _this.behaviourType = log.dictItemVOList;
          } else if (log.type == "dict_level") {
            _this.logLevel = log.dictItemVOList;
          }
        })
      })
    },
    /**
     * 日志查询重置
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogReset() {
      let obj = {
        // operateModule: "",
        // operateType: "",
        behaviourType: "", // 级别
        // level: "",
        hostIp: "", // IP
        description: "", // 操作行为
        username: "", // 用户名
        beginTime: "",// 开始时间
        endTime: "", // 结束时间
        result: "",
        logType: "option"
      };
      this.beginTime = "";
      this.endTime = "";
      this.searchForm = obj;
      this.sysLogPageData.pageInfo.current = 1;
      this.sysLogPageData.pageInfo.size = 10;
      this.sysLogQuery()
    },

    /**
     * 日志页码变化
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogSizeChange(val) {
      this.sysLogPageData.pageInfo.size = val;
      this.sysLogQuery();
    },

    /**
     * 日志当前页
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogCurrentChange(val) {
      this.sysLogPageData.pageInfo.current = val;
      this.sysLogQuery();
    },

    /**
     * 日志列表选中事件
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogSelectionChange(selection) {
      this.sysLogSelectIds = [];
      selection.forEach((item, index) => {
        this.sysLogSelectIds.push(item.id);
      });
      console.log(this.sysLogSelectIds)
    },

    /**
     * 日志添加
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogOpenCreateDialog() {
      this.sysLogDialogData.sysLogTitle = "添加";
      this.sysLogDialogData.visible = true;
      this.rules.password[0].required = true;
      this.sysLogDialogData.sysLogFormData = {
        logname: "",
        password: "",
        orgId: null,
        orgName: "",
        role: "",
        lockFlag: 1
      };
    },

    /**
     * 日志修改
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogOpenUpdateDialog(row) {
      this.sysLogDialogData.sysLogTitle = "修改";
      this.sysLogDialogData.visible = true;
      this.rules.password[0].required = false;
      this.sysLogDialogData.sysLogFormData = row;
    },

    /**
     * 日志保存
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogSaveOrUpdate() {
      let _this = this;
      this.$refs['sysLogForm'].validate((valid) => {
        if (valid) {
          let params = {
            id: this.sysLogDialogData.sysLogFormData.id,
            lockFlag: this.sysLogDialogData.sysLogFormData.lockFlag,
            orgId: this.sysLogDialogData.sysLogFormData.orgId,
            role: this.sysLogDialogData.sysLogFormData.role,
            logname: this.sysLogDialogData.sysLogFormData.logname,
          }
          if (this.sysLogDialogData.sysLogFormData.id) {
            sysLogApi.updateSysLogById(params).then((res) => {
              if (res.data) {
                this.$message.success("修改成功！");
                _this.sysLogDialogData.visible = false;
                _this.sysLogQuery();
              } else {
                this.$message.error("修改失败！");
              }
            });
          } else {
            sysLogApi.saveSysLog(this.sysLogDialogData.sysLogFormData).then((res) => {
              if (res.data) {
                this.$message.success("添加成功！");
                _this.sysLogDialogData.visible = false;
                _this.sysLogQuery();
              } else {
                this.$message.error("添加失败！");
              }
            });
          }
        } else {
          return false;
        }
      })
    },

    /**
     * 日志删除
     * @author wangwuhui
     * @date 2020-03-25 14:55:03
     */
    sysLogDeleteRecord(data) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sysLogApi.deleteSysLog(data.id).then((res) => {
          if (res.data > 0) {
            this.$message({
              type: 'success',
              message: '日志删除成功!'
            });
            this.sysLogQuery();
          } else {
            this.$message({
              type: 'error',
              message: '日志删除失败!'
            });
          }

        });
      });
    },
  },
}
</script>

<style>
  .float-right {
    float: right;
  }

  .dialogBox {
    display: flex;
    justify-content: center;
  }

  .margin-bottom-10 {
    margin-bottom: 10px;
  }

  .over-flow-hidden {
    overflow: hidden;
  }

</style>

